//
//  XCLocalStringTool.m
//  HOLLASMSLoginKit
//
//  Created by mao PengLin on 2019/10/11.
//  Copyright © 2019 mao PengLin. All rights reserved.
//

#import "XCLocalStringTool.h"
#import "Config.h"
#import "XCSMSTheme.h"

@interface XCLocalStringTool()

@property (nonatomic, strong) NSBundle *localBundle;

@end

@implementation XCLocalStringTool

+ (instancetype)sharedInstance {
    static XCLocalStringTool *_sharedInstance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _sharedInstance = [[XCLocalStringTool alloc] init];
    });
    return _sharedInstance;
}

- (instancetype)init {
    self = [super init];
    if (self) {
        NSString *languageCode = [[NSLocale preferredLanguages] objectAtIndex:0];
        NSBundle *bundle =[NSBundle bundleWithPath:[[NSBundle bundleForClass:[XCLocalStringTool class]] pathForResource:@"CAMPROSMSKit" ofType:@"bundle"]];
        NSString *path = [bundle pathForResource:[NSString stringWithFormat:@"Localizable/%@",languageCode] ofType:@"lproj"];
        if ((!path && [languageCode rangeOfString:@"zh-Hant"].location < 10) ||
            (!path && [languageCode rangeOfString:@"zh-HK"].location < 10) ||
            (!path && [languageCode rangeOfString:@"zh-TW"].location < 10) ||
            (!path && [languageCode rangeOfString:@"yue-Hant"].location < 10)) {
            path = [bundle pathForResource:[NSString stringWithFormat:@"Localizable/%@",@"zh-Hant-CN"] ofType:@"lproj"];
        }
        if (!path && languageCode.length > 2) {
            languageCode = [languageCode substringWithRange:NSMakeRange(0, 2)];
            path = [bundle pathForResource:[NSString stringWithFormat:@"Localizable/%@",languageCode] ofType:@"lproj"];
        }
        
        if (path && SupportMultiLanguages()) {
            self.localBundle = [NSBundle bundleWithPath:path];
        } else {
            path = [bundle pathForResource:@"Localizable/en" ofType:@"lproj"];
            self.localBundle = [NSBundle bundleWithPath:path];
        }
    }
    return self;
}

- (NSString *)getLocalStringWithKey:(NSString *)key {
    if (self.localBundle) {
       return  NSLocalizedStringFromTableInBundle(key, @"Localizable",
                                           self.localBundle, @"");
    }
    return @"";
}

@end
